/*
 * @Author: RYPY
 * @Date: 2021-03-14 21:18:58
 * @LastEditors: RYPY
 * @LastEditTime: 2021-03-14 22:12:12
 */
const express=require("express");
const {checkToken,Msg,getMD5Pwd}=require("../until/config");
const DB=require("../until/DB");
const formidable=require("formidable");
const path=require("path");
const fs=require("fs");
const router=express.Router();

//获取用户信息接口
router.get("/user",async (req,res,next)=>{
    let obj=checkToken(req.headers.authorization);
    let [err,result]=await DB.query(`select * from e_member where mid= '${obj.uid}'`);
    if(result.length>0){
        delete result[0].password;//将查询的数据中的密码删除
        res.send(Msg(200,"ok",result[0]));
    }else{
        next("没有该用户的数据");
    }
});

//修改用户信息接口
router.post("/updateuser",async(req,res,next)=>{
   let {realname,sex,birthdate,city,password='',repwd=""}=req.body;
   if(password!==repwd){
       next("两次密码不一致");
   } else{
       let obj=checkToken(req.headers.authorization);
       console.log(obj);
       let sql="";
       if(password!=""){
           sql=`update e_member set realname='${realname}',sex='${sex}',birthdate='${birthdate}',city='${city}',password='${getMD5Pwd(password)}' where mid='${obj.uid}'`;
       }else{
            sql=`update e_member set realname='${realname}',sex='${sex}',birthdate='${birthdate}',city='${city}' where mid='${obj.uid}'`;
       }
       console.log(sql);
       let [err,result]=await DB.query(sql);
       console.log(err);
       if(!err){
           res.send(Msg(200,"ok"));
       }else{
           next("请稍后再试");
       }
   }
});
//修改用户头像信息的接口
router.post("/uploadimg",async(req,res,next)=>{
    let obj=checkToken(req.headers.authorization);
    const form=formidable({
        uploadDir:path.join(__dirname,"../public/tempdir")
    });
    form.parse(req,async(err,fileds,files)=>{
        let suffixname=path.extname(files.curfile.name);//获取上传文件的后缀名
        //文件名必须是年月日时分秒+8位随机数
        let date=new Date();
        let newFileName=date.toLocaleDateString().replaceAll("/","")+date.toLocaleTimeString().replaceAll(":","").substring(2)+(Math.random()+"").substring(2,10)+suffixname;
        let oldpath=path.join(files.curfile.path);
        let newpath=path.join(__dirname,"../public/avatar",newFileName);
        try{
            fs.renameSync(oldpath,newpath);
            sql=`update e_member set head_photo_url='avatar/${newFileName}' where mid='${obj.uid}'`;
            let [err,result]=await DB.query(sql);
            res.send(Msg(200,"ok",`avatar/${newFileName}`));
        }catch{
            next("稍后再试");
        }
    })
});

module.exports=router;